package com.mygame.manager

import com.almasb.fxgl.dsl.FXGL
import com.almasb.fxgl.time.TimerAction
import com.mygame.components.TimerComponent
import javafx.util.Duration

object TimerManager {

    private var timerAction: TimerAction? = null
    private var timerListenerMap: MutableList<TimerComponent> = mutableListOf()

    fun add(listener: TimerComponent) {
        timerListenerMap.add(listener)
        if (timerAction == null){
            start()
        }
    }

    fun remove(listener: TimerComponent) {
        timerListenerMap.remove(listener)
    }

    fun start() {
        timerAction = FXGL.getGameTimer().runAtInterval({
            if (timerListenerMap.isNotEmpty()) {
                timerListenerMap.forEach { listener ->
                    listener.update()
                }
            }
        }, Duration.seconds(0.5))
    }

    fun stop() {
        timerAction?.expire()
    }
}